<?php

use com\gdl\newagk\interfaces\ExaminationServiceIf;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\newagk\dataobject\examination\ExaminationDTO;
use com\gdl\newagk\dataobject\examination\ExaminationRequestDTO;
date_default_timezone_set('PRC');//中华人民共和国时区
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use TencentYoutuyun\YouTu;
use FaceVisaYun\FaceVisa;
use TencentYoutuyun\Conf;
use TencentYoutuyun\Auth;

class api_ExaminationService extends api_Abstract implements ExaminationServiceIf
{
	public $monitor_arr = ['0'=>'--','1'=>'考前','2'=>'考中','4'=>'考后','3'=>'考前+考中','5'=>'考前+考后','6'=>'考中+考后','7'=>'考前+考中+考后'];
	//添加考场
    public function settingAdd(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

            $Exam_data = $Exam->filename ? $Exam->filename : [];
            $basic = new model_newagk_basic();
            $qbank = new model_newagk_qbank();
            $paper = new model_newagk_paper();


            $ques_name = $qbank->selectOne(['id' => $Exam_data['qid']], 'name');
            $paper_name = $paper->selectOne(['id' => $Exam_data['pid']], 'name,settings');
			$settings = unserialize($paper_name['settings']);
			$marks = 0;
			foreach($settings as $vs){
				if($vs[0]>3){
					$marks=1;
					break;
				}
			}
			if($marks && !$Exam_data['displayScore']){
				$result->code = 0;
				$result->message = '存在主观或填空题不能设置显示分数';
                $datas[] = ['id' => 0];
				return $result;
				
			}
			$basicName = $basic->selectOne(['basic' => $Exam_data['title']], 'id');
			if(!empty($basicName['id'])){
				$result->code = 0;
				$result->message = '考场名已存在';
                $datas[] = ['id' => 0];
				return $result;
				
			}
            $monitorRule = 0;
            if (!empty($Exam_data['start'])) {
                $Exam_data['start'] = json_decode($Exam_data['start'], true);
                $monitorRule += 1;
            }
            if (!empty($Exam_data['random'])) {
                $Exam_data['random'] = json_decode( $Exam_data['random'], true);
                $monitorRule += 2;
            }
            if (!empty($Exam_data['end'])) {
                $Exam_data['end'] = json_decode($Exam_data['end'], true);
                $monitorRule += 4;
            }
            /*             * 第一步先写配置** */
            $data = [
                'basic' => $Exam_data['title'],
                'pid' => (int) $Exam_data['pid'], //试卷id
                'pname' => $paper_name['name'], //试卷名
                'questions' => $Exam_data['qid'], //题库id
                'ques_name' => $ques_name['name'],
                'starttime' => $Exam_data['starttime'],
                'endtime' => $Exam_data['endtime'],
                'eventid' => $Exam_data['exam_types'] > 0 ? $Exam_data['eventid'] : 0,
				'createTime' => time(),
                'examnumber' => $Exam_data['num'], //考试次数
                'is_exam' => (int) $Exam_data['is_exam'], //0常规考场，1补考考场
                'displayScore' => (int) $Exam_data['displayScore'], //0显示分数 1不显示分数
                'archiving' => (int) $Exam_data['archiving'], //0不归档 1归档、
                'monitor' => (int) $Exam_data['monitor'], //监控1是启用 0是不启用
                'status' => (int) $Exam_data['status'],
                'typesId' => (int) $Exam_data['exam_types'], //1是工程考场 0是普通
                'admin_reg' => $Exam_data['reg'],
                'monitorRule' => $monitorRule,
            ];
	
            $ret = $basic->insert($data);
            $examId = $basic->lastInsertId(); //读取考场ID
            if ($Exam_data['monitor'] && $examId > 0) {
                //如果有需要验证就 保存验证规则
                self::ExamRules($examId, $Exam_data);

            }
            /*             * 第一步先写配置 end** */
            //$result->data[] = $this->monitor_arr;
            // $result->message = json_encode($monitorRule);
            //$result->message = json_encode($monitorRule);
            if ($examId > 1) {
                $result->code = 1;
				$result->message = '添加成功';
                $datas[] = ['id' => $examId];
            } else {
                $result->code = 0;
				$result->message = '添加失败';
                $datas[] = ['id' => 0];
            }

            $result->data = $datas;
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    //考场列表
    public function examList(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
		$down = $Exam->filename['down'] ?  $Exam->filename['down'] : '';
		$downid = $Exam->filename['id'] ?  explode(',',$Exam->filename['id']) : '';
        try {

			$filename = $Exam->filename ? $Exam->filename : [];
			$basic = new model_newagk_basic();
			$qbank = new model_newagk_qbank();
			$paper = new model_newagk_paper();
			
		//	$condition = "admin_reg!='{$filename['reg']}'";
		$condition = "1";
			if($filename['del']==true){
				$condition .= ' and isdelete=1';
			} else {
				$condition .= ' and isdelete=0';
			}

			if(!empty($filename['title'])){
				$condition .= ' and ( ';
				/***找试卷****/ 
				$papers = $paper->select("isdelete=0 and name like '%{$filename['title']}%'", 'id')->items; //admin_reg = '{$filename['reg']}' and 
				if(!empty($papers)){
					$paperid = [];
					foreach($papers as $v){
						$paperid[] = $v['id'];
					}
					$condition .= ' pid in('.implode(',',$paperid).') or';
				}
				/***找题库****/
				$qbanks = $qbank->select("admin_reg != '{$filename['reg']}' and isdelete=0 and name like '%{$filename['title']}%'", 'id')->items;
				if(!empty($qbanks)){
					$qbankid = [];
					foreach($qbanks as $vc){
						$qbankid[] = $vc['id'];
					}
					$condition .= ' questions in('.implode(',',$qbankid).') or';
				}
				/***找考场****/
				$condition .= " basic like '%{$filename['title']}%' )";
				
			}
			if(!empty($filename['startime'])){
				$condition .= ' and unix_timestamp(starttime)>='.strtotime($filename['startime']);
			}
			
			if(!empty($filename['endtime'])){
				$condition .= ' and unix_timestamp(starttime)<='.strtotime($filename['endtime']);
			}
			
			if($filename['exam']=='org'){
				$condition .= ' and typesId=1';
			} else if($filename['exam']=='ord'){
				$condition .= ' and typesId=0';
			}
			
			if($filename['isexam']!=''){
				$condition .= ' and is_exam='.$filename['isexam'];
			}
			if(!empty($filename['monitorRule'])){
				$condition .= ' and monitorRule='.$filename['monitorRule'];
			}
			if(!empty($filename['status'])){
				$condition .= ' and status='.$filename['status'];
			}
			if(!empty($filename['platform_name'])){
				
			}
			
		
			$items = 'id,basic,status,monitorRule,is_exam,typesId,endtime,starttime,ques_name,pname';
			$page = ($filename['page']-1) * $filename['pagesize'];
			if($down=='excels'){
				$groupBy = ' order by id desc';
			} else {
				$groupBy = ' order by id desc limit '.$page.','.$filename['pagesize'];
			}
			if($down=='excels' && !empty($downid) ){
				$dow_id = [0];
				foreach($downid as $v){
					$dow_id[] = intval($v);
				}
				$condition = ' id in('.implode(',',$dow_id).')';
			}
			
			$num = $basic->selectOne($condition,'count(*) num');
			$res = $basic->select($condition, $items, $groupBy)->items;

			/**第一步先写配置 end***/
			if(!empty($res)){
				$status = [1=>'启用',2=>'禁用',3=>'平台禁用','0'=>'未知'];
				$datas = [];
				if($down=='excels'){
					foreach($res as $v){
						$datas[] = [
									'id'=>$v['id'],
									'basicName'=>$v['basic'],
									'qbankName'=>$v['ques_name'],
									'paperName'=>$v['pname'],
									'time'=>$v['starttime'].'~'.$v['endtime'],
									'is_exam'=>$v['is_exam'] ? '补考' : '常规',
									'monitorDetails'=>$v['monitorRule'] ? $this->monitor_arr[$v['monitorRule']] : '',
									'status'=>$status[$v['status']],
									'platform_name'=>'安管控平台',
									];

						
					}
				} else {
					foreach($res as $v){
						$v['basic']=htmlspecialchars_decode($v['basic']);
						$v['ques_name']=htmlspecialchars_decode($v['ques_name']);
						$v['pname']=htmlspecialchars_decode($v['pname']);
						$v['monitorDetails'] = $this->monitor_arr[$v['monitorRule']];
						$v['platform_name'] = '安管控平台';
						$v['times']=$v['starttime'].'~'.$v['endtime'];
						$datas[] = $v;
					}
					
				}
				$res = $datas;
			}
			$result->data = $res;
			$result->message = $num['num'];
            $result->code = 1;
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	
	 //考场统计
    public function numExam(ExaminationDTO $Exam)
    {
        $result = new ResultDO();
		$reg = $Exam->reg ?  $Exam->reg : '';
		$result->code=0;
		if($reg==''){
			
			$result->message = '缺少参数';
			return $result;
		}
        try {

			$basic = new model_newagk_basic();
			$condition = " status=1 and isdelete=0 ";
			$items = 'count(*) num';
			$datime = time();
			/***考试未开始***/
			$start = $basic->selectOne($condition.' and UNIX_TIMESTAMP(starttime)>'.$datime,'count(*) num');
			/***考试未开始 end***/
			
			/***考试进行中***/
			$process = $basic->selectOne($condition.' and UNIX_TIMESTAMP(starttime)<'.$datime.' and UNIX_TIMESTAMP(endtime)>'.$datime,'count(*) num');
			/***考试进行中 end***/
			
			/***考试已结束**/
			$end = $basic->selectOne($condition.' and UNIX_TIMESTAMP(endtime)<'.$datime,'count(*) num');
			/***考试已结束 end***/
			
			$result->data[] = ['start'=>$start['num'],'process'=>$process['num'],'end'=>$end['num'],'totals'=>$start['num']+$process['num']+$end['num']];
            $result->code = 1;

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->message = '异常';
        }
        return $result;
    }


    //考场管理列表
    public function examManageList(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

            $filename = $Exam->filename ? gdl_lib_BaseUtils::getStr( $Exam->filename) : [];
            $basic = new model_newagk_basic();
            $basic_user = new model_newagk_basicuser();
            $exam_session_model = new model_newagk_examsession();
            $platform_model = new model_newagk_platform();
            $examspapers_model = new model_newagk_examspapers();
//			$condition = "admin_reg='{$Exam_data['reg']}'";
            $condition = " agk_basic.status = 1 and agk_basic.isdelete = 0 ";
            $time = time();

            if(!empty($filename['basic_id'])){
                $condition .= ' and agk_basic.id in ('.$filename['basic_id']." )";
            }else{
                if ($filename['adminUserId']){//通过后台登录用户ID查询考场ID
                    $condition .= " and agk_basic.admin_reg in ( (select reg from agk_admin_user where id = {$filename['adminUserId']}) ) ";
                }elseif ($filename['reg']){
                    $condition .= " and agk_basic.id in (select id from agk_basic where admin_reg = {$filename['reg']}) ";
                }

                //获取该用户下面的所有考场id
//                if ($filename['adminUserId']){
//                    $condition .= " and agk_basic.id in (select basicid from agk_basic_binding where adminUserId = {$filename['adminUserId']} and LossTime>{$time} ) ";
//                }elseif ($filename['reg']){
//                    $condition .= " and agk_basic.id in (select id from agk_basic where admin_reg = {$filename['reg']}) ";
//                }
            }

            if(!empty($filename['title'])){
                /***找考场****/
                $condition .= " and agk_basic.basic like '%{$filename['title']}%' ";

            }
            if(!empty($filename['platform_title'])){
                /***找考场****/
                $condition .= " and ap.reals like '%{$filename['platform_title']}%' ";

            }

            if(!empty($filename['starttime'])){
                $condition .= " and  UNIX_TIMESTAMP(agk_basic.starttime)>='".strtotime($filename['starttime'])."' ";
            }

            if(!empty($filename['endtime'])){
                $condition .= " and  UNIX_TIMESTAMP(agk_basic.starttime)<='".strtotime($filename['endtime'])."' ";;
            }

            if($filename['typesId']!=='' && $filename['typesId']!==null && $filename['typesId']>=0){
                $condition .= ' and typesId='.$filename['typesId'];
            }

            if(!empty($filename['is_exam'])){
                $condition .= ' and is_exam='.$filename['is_exam'];
            }
            if(!empty($filename['monitorRule'])){
                $condition .= ' and monitorRule='.$filename['monitorRule'];
            }
            if ($filename['basic_status']==1){// 1进行中 2未开始 3已结束
                $condition .= " and UNIX_TIMESTAMP(starttime)<{$time} and  UNIX_TIMESTAMP(endtime)>{$time}";
            }elseif ($filename['basic_status']==2){
                $condition .= " and UNIX_TIMESTAMP(starttime)>{$time}";
            }elseif ($filename['basic_status']==3){
                $condition.=" and UNIX_TIMESTAMP(endtime)<{$time} ";
            }
            $items = 'agk_basic.id,basic,agk_basic.status,monitorRule,is_exam,typesId,endtime,starttime,ques_name,pname,agk_basic.admin_reg';
            $page = ($filename['page']-1) * $filename['pagesize'];
            $groupBy = ' order by agk_basic.id desc limit '.$page.','.$filename['pagesize'];
            $leftjoin = array('agk_platform as ap' => 'agk_basic.admin_reg=ap.admin_reg');
            $res = $basic->select($condition, $items, $groupBy,"",$leftjoin)->items;

			
//            if(!empty($filename['basic_id'])){
//                $basic_condition = ' agk_basic.id in ('.$filename['basic_id']." )";
//            }else{
//                //获取该用户下面的所有考场id
//                if ($filename['adminUserId']){
//                    $basic_condition = " agk_basic.admin_reg in ( (select reg from agk_admin_user where id = {$filename['adminUserId']}) ) ";
////                    $basic_condition = " agk_basic.id in (select basicid from agk_basic_binding where adminUserId = {$filename['adminUserId']} and LossTime>{$time} ) ";
//                }elseif ($filename['reg']){
//                    $basic_condition = " agk_basic.id in (select id from agk_basic where admin_reg = {$filename['reg']}) ";
//                }
//            }
            $count = $basic->selectOne($condition, "count(agk_basic.id) as num"," order by agk_basic.id desc ","",$leftjoin);
            /**第一步先写配置 end***/
            if ($res){
                $basics = array_column($res,'id');
                $basicids = implode(',',$basics);
                $admin_regs = array_column($res,'admin_reg');
                $admin_regs = implode("','",$admin_regs);
                //获取该平台下面不同考场下面的应参考人数
                $basic_users_should= $basic_user->select(" basic_id in ({$basicids}) and `status`=1 ", "basic_id,count(identity_id) num"," group by basic_id ")->items;
                if ($basic_users_should){
                    $basic_users_should = $this->arrayValueByKey($basic_users_should,'basic_id');
                }
                //获取该平台下面所有考场 进行中和结束的已参考人数
                    $ever_arr= array();
                    //获取进行中人数
                    $basic_users_ever= $exam_session_model->select(" basicid in ({$basicids}) and `status`=1 and identity_id not in (select identity_id from agk_exams_papers where basicid in ({$basicids})) ", "basicid,count(identity_id) num"," group by basicid ")->items;
                    if ($basic_users_ever){
                        $basic_users_ever = $this->arrayValueByKey($basic_users_ever,'basicid');
                    }
                    $over_nums = [];
                    //获取结束的人数
                    $basic_users_over= $examspapers_model->select(" basicid in ({$basicids}) ", "identity_id,basicid,count(identity_id) num,SUM( IF(score >= passscore, 1, 0) ) as gt"," group by basicid,identity_id")->items;
                    if ($basic_users_over){
//                        $basic_users_over = $this->arrayValueByKey($basic_users_over,'basicid');
                        foreach ($basic_users_over as $oveK=>$oveV){
                            if ($oveV['num']>=1){
                                $over_nums[$oveV['basicid']]['num'] +=1;
                            }
                            if ($oveV['gt']>=1){
                                $over_nums[$oveV['basicid']]['gt'] +=1;
                            }
                        }
                    }
                //获取考场所属平台
                $basic_platform= $platform_model->select(" admin_reg in ('{$admin_regs}') and `status`=1 ", "reals,admin_reg")->items;
                if ($basic_platform){
                    $basic_platform = $this->arrayValueByKey($basic_platform,'admin_reg');
                }

                foreach ($res as &$value){
                    $value['users_should_nums'] = 0;
                    $value['users_ever_nums'] = 0;
                    $value['users_not_nums'] = 0;
                    $value['users_doing_nums'] = 0;
                    $value['users_pass_nums'] = 0;
                    $value['users_pass'] = "0%";
                    $value['platform_name'] = '本平台';
                    $value['basic_time'] = $value['starttime']."~~".$value['endtime'];
                    $endtime= strtotime($value['endtime']);
                    $starttime= strtotime($value['starttime']);
                    if ($starttime>$time){
						$isPigeonhole = 1;
                        $timeRemaining = "距考试开始时间剩".$this->timeRemaining($starttime)."（考试未开始）";
                    }elseif ($starttime<$time && $time<$endtime){
						$isPigeonhole = 2;
                        $timeRemaining = "距考试结束时间剩".$this->timeRemaining($endtime)."（考试进行中）";
                    }else{
						$isPigeonhole = 3;
                        $timeRemaining = "考试已结束";
                    }
                    $value['timeRemaining'] = $timeRemaining;
					$value['isPigeonhole'] = $isPigeonhole;
                    foreach ($basic_users_should as $bk=>$bv){
                        if ($value['id']==$bk){
                            $value['users_should_nums'] = $bv['num']?$bv['num']:0;
                        }
                    }
                    foreach ($basic_users_ever as $bk=>$bv){
                        if ($value['id']==$bk){
                            $value['users_doing_nums'] = $bv['num']?$bv['num']:0;
                        }
                    }
                    foreach ($over_nums as $bke=>$bve){
                        if ($value['id']==$bke){
                            $value['users_ever_nums'] = $bve['num']?$bve['num']:0;
                        }
                    }
                    foreach ($over_nums as $bke=>$bve){
                        if ($value['id']==$bke){
                            $value['users_pass_nums'] = $bve['gt']?$bve['gt']:0;
                        }
                    }
                    foreach ($basic_platform as $bkp=>$bvp){
                        if ($value['admin_reg']==$bkp){
                            $value['platform_name'] = $bvp['reals'];
                        }
                    }
                    $value['users_ever_nums'] = $value['users_ever_nums'] + $value['users_doing_nums'];
                    $value['users_not_nums'] = $value['users_should_nums']>=$value['users_ever_nums']?($value['users_should_nums']-$value['users_ever_nums']):0;//未参考人数
                    $value['users_pass'] = round($value['users_pass_nums']/$value['users_should_nums']*100,2)."%";//未参考人数
                }
            }
            $result->data = $res;
            $result->message = json_encode($count?$count['num']:0);
            if ($res) {
                $result->code = 1;
            } else {
                $result->code = 0;
            }
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    //考场检测记录列表
    public function examViolationList(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

            $filename = $Exam->filename ? gdl_lib_BaseUtils::getStr( $Exam->filename) : [];
            $basic_model = new model_newagk_basic();
            $violation_model = new model_newagk_violation();
//			$condition = "admin_reg='{$Exam_data['reg']}'";
            $time =time();
            $condition = " 1 and agk_violation.isdelete=0 ";
            if(!empty($filename['title'])){
                $condition .= " and agk_violation.basic like '%{$filename['title']}%' ";
            }
            if(!empty($filename['userName'])){//userIdcard
                if ($this->isIdCard($filename['userName'])){
                    $condition .= " and userIdcard like '%{$filename['userIdcard']}%' ";
                }else{
                    $condition .= " and userName like '%{$filename['userName']}%' ";
                }
            }
            if(!empty($filename['violation_id'])){
                $condition .= " and agk_violation.id in ({$filename['violation_id']}) ";
            }
            if(!empty($filename['basic_id'])){
                $condition .= " and basicId = '{$filename['basic_id']}' ";
            }else{
                if ($filename['adminUserId']){//通过后台登录用户ID查询考场ID
                    $condition .= " and ab.admin_reg in ( (select reg from agk_admin_user where id = {$filename['adminUserId']}) ) ";
                }elseif ($filename['reg']){
                    $condition .= " and ab.id in (select id from agk_basic where admin_reg = {$filename['reg']}) ";
                }
                //获取该平台下面的所有考场id
//                if ($filename['adminUserId']){
//                    $condition .= " and basicId in (select basicid from agk_basic_binding where adminUserId = {$filename['adminUserId']} and LossTime>{$time} ) ";
//                }elseif ($filename['reg']){
//                    $condition .= " and basicId in (select id from agk_basic where admin_reg = {$filename['reg']}) ";
//                }
            }
            if($filename['status']!=='' && $filename['status']!==null && $filename['status']>=0){
                $condition .= ' and agk_violation.status='.$filename['status'];
            }
            if($filename['verification']!=='' && $filename['verification']!==null && $filename['verification']>=0){
                $condition .= ' and verification='.$filename['verification'];
            }
            if(!empty($filename['detection_type'])){
                $condition .= ' and type ='.$filename['detection_type'];
            }
            if ($filename['basic_status']==1){// 1进行中 2未开始 3已结束
                $condition .= " and UNIX_TIMESTAMP(ab.starttime)<{$time} and  UNIX_TIMESTAMP(ab.endtime)>{$time}";
            }elseif ($filename['basic_status']==2){
                $condition .= " and UNIX_TIMESTAMP(ab.starttime)>{$time}";
            }elseif ($filename['basic_status']==3){
                $condition.=" and UNIX_TIMESTAMP(ab.endtime)<{$time} ";
            }
            $items = 'agk_violation.*,ab.typesId,ab.id as basicId';
            $page = ($filename['page']-1) * $filename['pagesize'];
            $groupBy = ' order by id desc limit '.$page.','.$filename['pagesize'];
            $leftjoin = array('agk_basic as ab' => 'agk_violation.basicId=ab.id');
            $res = $violation_model->select($condition, $items, $groupBy,"",$leftjoin)->items;
            $basicId_condition = " agk_violation.isdelete=0 ";
            if(!empty($filename['basic_id'])){
                $basicId_condition .= " and basicId = '{$filename['basic_id']}' ";
            }else{
                if ($filename['adminUserId']){//通过后台登录用户ID查询考场ID
                    $basicId_condition .= " and ab.admin_reg in ( (select reg from agk_admin_user where id = {$filename['adminUserId']}) ) ";
                }elseif ($filename['reg']){
                    $basicId_condition .= " and basicId in (select id from agk_basic where admin_reg = {$filename['reg']}) ";
                }
                //获取该平台下面的所有考场id
//                if ($filename['adminUserId']){
//                    $basicId_condition .= " and basicId in (select basicid from agk_basic_binding where adminUserId = {$filename['adminUserId']} and LossTime>{$time} ) ";
//                }elseif ($filename['reg']){
//                    $basicId_condition .= " and basicId in (select id from agk_basic where admin_reg = {$filename['reg']}) ";
//                }
            }
            $count = $violation_model->selectOne($basicId_condition, "count(agk_violation.id) as num",'','',$leftjoin);
//            $result->message = json_encode($filename['status']);
            if ($res) {
                $basic_platform = array();
                //获取考场进行状态
                if(!empty($filename['basic_id'])){
                    $condition = " id = {$filename['basic_id']} and `status`=1 ";

                }else{
                    if ($filename['adminUserId']){//通过后台登录用户ID查询考场ID
                        $condition .= " and admin_reg in ( (select reg from agk_admin_user where id = {$filename['adminUserId']}) ) ";
                    }elseif ($filename['reg']){
                        $condition = " and admin_reg = {$filename['reg']}) ";
                    }
                    //获取该平台下面的所有考场id
//                    if ($filename['adminUserId']){
//                        $condition = " id in (select basicid from agk_basic_binding where adminUserId = {$filename['adminUserId']} and LossTime>{$time} ) and `status`=1 ";
//                    }elseif ($filename['reg']){
//                        $condition = " id in (select id from agk_basic where admin_reg = {$filename['reg']}) and `status`=1 ";
//                    }
                }

                $basic_platform= $basic_model->select($condition, "id,starttime,endtime")->items;
                if ($basic_platform){
                    $basic_platform = $this->arrayValueByKey($basic_platform);

                    foreach ($basic_platform as &$valp){
                        if (strtotime($valp['starttime'])>$time){
                            $valp['basic_status'] = "考试未开始";
                        }elseif (strtotime($valp['starttime'])<$time &&  strtotime($valp['endtime'])>$time){
                            $valp['basic_status'] = "考试进行中";
                        }elseif (strtotime($valp['endtime'])<$time){
                            $valp['basic_status'] = "考试已结束";
                        }
                    }
                    foreach ($res as &$val){
                        $val['userIdcard']   = substr_replace($val['userIdcard'], '****', 3, 11);
                        $val['type']          = ($val['type'] && $val['type']==1)?"人脸识别":"操作监测";
                        $val['verification_staus']          = ($val['verification'] && $val['verification']==1)?"验证通过":"验证异常";
                        $val['violation_time']          = ($val['rule'] && $val['rule']=='random')?"考中监测(".$val['startTime'].")":($val['rule']=='start'?"考前监测(".$val['startTime'].")":"考后监测(".$val['startTime'].")");
                        $val['basic_status'] = "考试未开始";
                        foreach ($basic_platform as $pl_key=>$pl_val){
                            if ($val['basicId']==$pl_key){
                                $val['basic_status'] = $pl_val['basic_status'];
                            }
                        }
//                        if(!empty($filename['basic_status'])){// 1进行中 2未开始 3已结束
//                            if ($filename['basic_status']==1 && $val['basic_status']!=="考试进行中"){
//                                $val='';
//                            }elseif ($filename['basic_status']==2 && $val['basic_status']!=="考试未开始"){
//                                $val='';
//                            }elseif ($filename['basic_status']==3 && $val['basic_status']!=="考试已结束"){
//                                $val='';
//                            }
//                        }
                    }
                    $res = array_filter($res);
                }
                $result->data = $res;
                $result->message = json_encode($count?$count['num']:0);
                $result->code = 1;
            } else {
                $result->code = 0;
//                $result->message = json_encode($violation_model);
            }
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    public function deleteViolation(ExaminationRequestDTO $Exam){
        $id = $Exam->id ? gdl_lib_BaseUtils::getStr($Exam->id, 'int') : '0'; # 检测记录ID
        $result = new ResultDO();
        try{
            $result->code = 0;
            $result->success = true;
            if(!$id){
                $result->message = "请填写检测记录ID";
                return $result;
            }
            $violationModel = new model_newagk_violation();
            $arw = $violationModel->update(['id'=>$id]," isdelete=1 ");
            if ($arw){
                $result->message ='成功';
                $result->code = 1;
            }else{
                $result->message ='失败';
            }

            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    //考场成绩列表列表 basic_id必传
    public function getExamPapersList(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {
            $filename = $Exam->filename ? gdl_lib_BaseUtils::getStr( $Exam->filename) : [];
			$ex_type  = $Exam->type?gdl_lib_BaseUtils::getStr($Exam->type) : '';//1:身份证显示完全
//            $basic_model = new model_newagk_basic();
            $basic_user_model = new model_newagk_basicuser();
            $basic_user_model_s = new model_newagk_basicuser();
            $examspapers_model = new model_newagk_examspapers();
            $examsession_model = new model_newagk_examsession();
            $violation_model = new model_newagk_violation();
//			$condition = "admin_reg='{$Exam_data['reg']}'";
            $time = time();
            $user_arr  = array();
            //获取该考场正在考试中人员
            $user_doinfo = $examsession_model->select(['basicid'=>$filename['basic_id'],'status'=>1], '*')->items;
            $user_doinfo_ids = array_column($user_doinfo,'identity_id');
            //获取该考场所有已经交卷人员
//            $make_condition = ['basicid'=>$filename['basic_id']];
            $make_condition = " basicid = {$filename['basic_id']} ";
            $user_makeinfo = $examspapers_model->select($make_condition)->items;
            $user_makeinfo_ids = array_column($user_makeinfo,'identity_id');
            //获取该考场所有异常人员
            $user_violationinfo = $violation_model->select(['basicId'=>$filename['basic_id'],'verification'=>0], "id,identity_id,basicId")->items;
            $user_violationinfo_ids = array_column($user_violationinfo,'identity_id');
            $user_violationinfo = $this->arrayValueByKey($user_violationinfo,'identity_id');
            //获取考场内的所有人员id

            $condition = " basic_id = '{$filename['basic_id']}' and agk_basic_user.`status`=1 ";

            if (!empty($filename['score'])){//分数限制
                $con_score = explode('-',$filename['score']);
                $min_score = $con_score[0]?$con_score[0]:0;
                $max_score = $con_score[1]?$con_score[1]:999;
                $condition.=" and  aep.modified>={$min_score} and aep.modified<={$max_score} ";
            }elseif (!empty($filename['startGrade']) && empty($filename['endGrade'])){
                $condition.=" and aep.modified>={$filename['startGrade']} ";
            }elseif (!empty($filename['endGrade']) && empty($filename['startGrade'])){
                $condition.=" and aep.modified<={$filename['endGrade']} ";
            }elseif (!empty($filename['endGrade']) && !empty($filename['startGrade'])){
                $condition.=" and  aep.modified>={$filename['startGrade']} and aep.modified<={$filename['endGrade']} ";
            }
            if (!empty($filename['terminal'])){//考试终端 1手机app 2平板app 3pc端
                $condition.=" and aep.terminal ={$filename['terminal']}";
            }
            if (!empty($filename['ispass'])){////考场状态 1 合格 2 不合格 3 未阅卷
                if ($filename['ispass']==1){
                    $condition.=" and aep.modified >=aep.passscore ";
                }elseif ($filename['ispass']==2){
                    $condition.=" and aep.modified < aep.passscore ";
                }elseif ($filename['ispass']==3){
                    $condition.=" and aep.is_read =2 ";
                }
            }
            if (!empty($filename['type'])){//考场状态 1正常 2异常
                $violationids = implode(',',$user_violationinfo_ids);
                if ($filename['type']==2){
                    $condition.=" and agk_basic_user.identity_id in ($violationids) ";
                }elseif($filename['type']==1){
                    if (!empty($violationids)){
                        $condition.=" and agk_basic_user.identity_id not in({$violationids})";
                    }
                }
            }
            if (!empty($filename['status'])){// 1未开始 2考试中 3正常 4缺考 5作弊
                $makeinfoids = implode(',',$user_makeinfo_ids);//交卷人员id
                $makeinfoids_str = $makeinfoids?$makeinfoids:0;
                $doinfoids = implode(',',$user_doinfo_ids);//正在考试人员id
                $doinfoids_str = $doinfoids?$doinfoids:0;
                if ($filename['status']==3){
                    $condition.=" and agk_basic_user.identity_id in ($makeinfoids_str) ";
                }elseif($filename['status']==2){
                    $condition.=" and agk_basic_user.identity_id in({$doinfoids_str})";
                }elseif($filename['status']==5){
                    $condition.=" and aep.status = 2";
                }elseif($filename['status']==4 || $filename['status']==1){
                    $not_user_ids =  array_merge($user_makeinfo_ids,$user_doinfo_ids);
                    $not_user_ids_str = $not_user_ids?implode(',',$not_user_ids):0;
                    $condition.=" and agk_basic_user.identity_id not in({$not_user_ids_str})";
                }
            }
            if(!empty($filename['title'])){
                if ($this->isIdCard($filename['title'])){//是身份证
                    $condition.=" and agk_basic_user.idcard = '{$filename['title']}'";
                }elseif (is_numeric($filename['title']) && $this->is_mobile($filename['title'])){
                    $condition.=" and agk_basic_user.phone = {$filename['title']}";
                }else{//考生姓名
                    $condition.=" and agk_basic_user.usertruename like '%{$filename['title']}%' ";
                }
            }
            $items = 'agk_basic_user.*,aep.id as epaperid,ab.starttime as basic_starttime,ab.endtime as basic_endtime';
            $page = ($filename['page']-1) * $filename['pagesize'];
            $groupBy = ' order by aep.id desc limit '.$page.','.$filename['pagesize'];
            $leftjoin = array(
                'agk_exams_papers as aep' => "agk_basic_user.identity_id=aep.identity_id and aep.basicid={$filename['basic_id']}",
                'agk_basic as ab' => "agk_basic_user.basic_id=ab.id",
            );

            $userinfo_all = $basic_user_model->select($condition,$items,$groupBy,"",$leftjoin)->items;//分页需求
	
            $user_identityid_all = $basic_user_model_s->select($condition,"identity_id")->items;//找出所有人员ID
            $userinfo_all_ids = array_column($user_identityid_all,'identity_id');
            if (!$user_identityid_all){
                $make_condition = " basicid = {$filename['basic_id']} ";
                if (!empty($filename['score'])){//分数限制
                    $con_score = explode('-',$filename['score']);
                    $min_score = $con_score[0]?$con_score[0]:0;
                    $max_score = $con_score[1]?$con_score[1]:999;
                    $make_condition.=" and  agk_exams_papers.modified>={$min_score} and agk_exams_papers.modified<={$max_score} ";
                }elseif (!empty($filename['startGrade']) && empty($filename['endGrade'])){
                    $make_condition.=" and agk_exams_papers.modified>={$filename['startGrade']} ";
                }elseif (!empty($filename['endGrade']) && empty($filename['startGrade'])){
                    $make_condition.=" and agk_exams_papers.modified<={$filename['endGrade']} ";
                }elseif (!empty($filename['endGrade']) && !empty($filename['startGrade'])){
                    $make_condition.=" and  agk_exams_papers.modified>={$filename['startGrade']} and agk_exams_papers.modified<={$filename['endGrade']} ";
                }
                if (!empty($filename['terminal'])){//考试终端 1手机app 2平板app 3pc端
                    $make_condition.=" and agk_exams_papers.terminal ={$filename['terminal']}";
                }
                if (!empty($filename['ispass'])){////考场状态 1 合格 2 不合格 3 未阅卷
                    if ($filename['ispass']==1){
                        $make_condition.=" and agk_exams_papers.modified >=agk_exams_papers.passscore ";
                    }elseif ($filename['ispass']==2){
                        $make_condition.=" and agk_exams_papers.modified < agk_exams_papers.passscore ";
                    }elseif ($filename['ispass']==3){
                        $make_condition.=" and agk_exams_papers.is_read =2 ";
                    }
                }
                if (!empty($filename['type'])){//考场状态 1正常 2异常
                    $violationids = implode(',',$user_violationinfo_ids);
                    if ($filename['type']==2){
                        $make_condition.=" and agk_exams_papers.identity_id in ($violationids) ";
                    }elseif($filename['type']==1){
                        if (!empty($violationids)){
                            $make_condition.=" and agk_exams_papers.identity_id not in({$violationids})";
                        }
                    }
                }
                if (!empty($filename['status'])){// 1未开始 2考试中 3正常 4缺考 5作弊
                    $makeinfoids = implode(',',$user_makeinfo_ids);//交卷人员id
                    $makeinfoids_str = $makeinfoids?$makeinfoids:0;
                    $doinfoids = implode(',',$user_doinfo_ids);//正在考试人员id
                    $doinfoids_str = $doinfoids?$doinfoids:0;
                    if ($filename['status']==3){
                        $make_condition.=" and agk_exams_papers.identity_id in ($makeinfoids_str) ";
                    }elseif($filename['status']==2){
                        $make_condition.=" and agk_exams_papers.identity_id in({$doinfoids_str})";
                    }elseif($filename['status']==5){
                        $make_condition.=" and agk_exams_papers.status = 2";
                    }elseif($filename['status']==4 || $filename['status']==1){
                        $not_user_ids =  array_merge($user_makeinfo_ids,$user_doinfo_ids);
                        $not_user_ids_str = $not_user_ids?implode(',',$not_user_ids):0;
                        $make_condition.=" and agk_exams_papers.identity_id not in({$not_user_ids_str})";
                    }
                }
                if(!empty($filename['title'])){
                    if ($this->isIdCard($filename['title'])){//是身份证
                        $make_condition.=" and au.idcard = '{$filename['title']}'";
                    }elseif (is_numeric($filename['title']) && $this->is_mobile($filename['title']) ){
                        $make_condition.=" and auc.contactPhone = {$filename['title']}";
                    }else{//考生姓名
                        $make_condition.=" and au.realName like '%{$filename['title']}%' ";
                    }
                }
                $leftjoin = array(
                    'agk_basic as ab' => "agk_exams_papers.basicid=ab.id",
                    'agk_user_company as auc' => "agk_exams_papers.identity_id=auc.id",
                    'agk_user as au' => "auc.userId=au.userId",
                );
                $groupBy = ' order by agk_exams_papers.id desc limit '.$page.','.$filename['pagesize'];
                $items = 'au.userName,au.realName usertruename,au.idcard,auc.contactPhone phone,agk_exams_papers.*,agk_exams_papers.id as epaperid,ab.starttime as basic_starttime,ab.endtime as basic_endtime';
                $user_makeinfo = $examspapers_model->select($make_condition,$items,$groupBy,"",$leftjoin)->items;
                $user_makeinfo_ids = array_column($user_makeinfo,'identity_id');
            }
//            $count_users = count($user_identityid_all);
            $all_count = array_merge($userinfo_all_ids,$user_makeinfo_ids);//把所有考试试卷的人员Id和所有考试人员的合并
            $all_count = array_count_values($all_count);//取出每个人员ID的重复数量 数量大于1的为考试人员ID
            $all_counts = 0;
            foreach ($all_count as $allK=>$allV){
                if ($allV>1){
                    $all_counts +=$allV-1;
                }else{
                    $all_counts +=$allV;
                }
            }

            if ($userinfo_all){
                //找出所有缺考人员
                $not_basic_ids =  array_diff($userinfo_all_ids,$user_doinfo_ids,$user_makeinfo_ids);
				
//                            $result->message = json_encode($examspapers_model);
                foreach ($userinfo_all as $key=>$value){
                    $user_arr[$key]['paper_id'] = 0;
                    $user_arr[$key]['basic_id'] = $filename['basic_id'];
                    $user_arr[$key]['identity_id'] = $value['identity_id'];
                    $user_arr[$key]['usertruename'] = $value['usertruename'];
					if($ex_type && $ex_type==1){
						$user_arr[$key]['idcard'] = "@".$value['idcard'];
					}else{
						$user_arr[$key]['idcard'] = substr_replace($value['idcard'], '****', 3, 11);
					}
                    $user_arr[$key]['phone'] = $value['phone'];
                    $user_arr[$key]['basic_status'] = "未开始";
                    $user_arr[$key]['basic_start_time'] = "----";
                    $user_arr[$key]['basic_type'] = "----";
                    $user_arr[$key]['score'] = "----";
                    $user_arr[$key]['ispass'] = "----";
                    $user_arr[$key]['ispass_status'] = 0;
                    $user_arr[$key]['time'] = "----";
                    $user_arr[$key]['remark'] = "----";
                    $user_arr[$key]['terminal'] = "----";//手机app
                    $user_arr[$key]['basic_type_id'] = 0;
                    if (!in_array($value['identity_id'],$not_basic_ids)){//判断是否为缺考人员
                        //if (in_array($value['identity_id'],$user_doinfo_ids)){//进行中人员
                        //    foreach ($user_doinfo as $dk=>$dv){
						//		  $user_arr[$key]['terminal'] = '手机app';
                        //        if ($value['identity_id']==$dv['identity_id']){
                        //            $user_arr[$key]['basic_status'] = "考试中";
                         //           $user_arr[$key]['basic_start_time'] = date('Y-m-d H:i:s',$dv['starttime']);
                        //            if (in_array($dv['identity_id'],$user_violationinfo_ids)){
                        //                $user_arr[$key]['basic_type'] = "异常";
                        //                $user_arr[$key]['basic_type_id'] = $user_violationinfo[$dv['identity_id']]['id'];//异常ID
                        //            }else{
                        //                $user_arr[$key]['basic_type'] = "无异常";
                        //            }
                         //       }
                         //   }
                        //}else
							if (in_array($value['identity_id'],$user_makeinfo_ids)){//考试完成人员

                            foreach ($user_makeinfo as $mk=>$mv){
								$user_arr[$key]['terminal'] = '手机app';
                                if ($value['identity_id']==$mv['identity_id'] && $value['epaperid']==$mv['id']){
                                    $user_arr[$key]['remark'] = $mv['remark'];
                                    $user_arr[$key]['paper_id'] = $mv['id'];
                                    if (in_array($mv['identity_id'],$user_violationinfo_ids)){
                                        $user_arr[$key]['basic_type'] = "异常";
                                        $user_arr[$key]['basic_type_id'] = $user_violationinfo[$mv['identity_id']]['id'];//异常ID
                                    }else{
                                        $user_arr[$key]['basic_type'] = "无异常";
                                    }
                                    if ($mv['status']==1){
                                        $user_arr[$key]['basic_status'] = "正常";
                                    }elseif ($mv['status']==2){
                                        $user_arr[$key]['basic_status'] = "作弊";
                                    }
                                    $user_arr[$key]['time'] = $this->secToTime($mv['time']);
                                    $user_arr[$key]['basic_start_time'] = date('Y-m-d H:i:s',$mv['starttime']);

                                    if ($mv['is_read']==3){
                                        $user_arr[$key]['ispass'] = ($mv['modified']>=$mv['passscore'])?"合格":"不合格";
                                        $user_arr[$key]['ispass_status'] = ($mv['modified']>=$mv['passscore'])?1:2;
                                        $user_arr[$key]['score'] = $mv['modified'];
                                    }elseif($mv['is_read']==2){
                                        $user_arr[$key]['ispass'] = "未阅卷";
                                        $user_arr[$key]['ispass_status'] = 3;
                                    }else{
                                        $user_arr[$key]['score'] = $mv['modified'];
                                        $user_arr[$key]['ispass'] = ($mv['modified']>=$mv['passscore'])?"合格":"不合格";
                                        $user_arr[$key]['ispass_status'] = ($mv['modified']>=$mv['passscore'])?1:2;
                                    }
                                    $user_arr[$key]['terminal'] = ($mv['terminal']==1)?"手机app":($mv['terminal']==2?"平板app":"pc端");
                                }
                            }

                        }
                    }else{
                        $endtime= strtotime($value['basic_endtime']);
                        $starttime= strtotime($value['basic_starttime']);
						$user_arr[$key]['score'] = 0;
                        if ($starttime<$time && $time<$endtime){//考试中
                            $user_arr[$key]['basic_status'] = "未考试";
							$user_arr[$key]['score'] = "----";
							$user_arr[$key]['ispass_status'] = 0;
                        }elseif($time<$starttime){//考试未开始
                            $user_arr[$key]['basic_status'] = "未考试";
							$user_arr[$key]['score'] = "----";
							      // $user_arr[$key]['score'] = "----";
                        }else{//考试已结束
                            $user_arr[$key]['basic_status'] = "缺考";
							$user_arr[$key]['ispass'] = "不合格";
							$user_arr[$key]['score'] = "0";
							$user_arr[$key]['ispass_status'] = 2;
                        }
                 
                        $user_arr[$key]['ispass'] = "不合格";
                    }
					
                }

//                $result->message = json_encode($condition);
                if ($user_arr) {
                    $result->data = $user_arr;
                    $result->message = json_encode($all_counts);
                    $result->code = 1;
                } else {
                    $result->code = 0;
                }
            }else{
                if ($user_makeinfo){
                    foreach ($user_makeinfo as $mk=>$mv){
                        $user_arr[$mk]['usertruename'] = $mv['usertruename'];
                        $user_arr[$mk]['idcard'] = $mv['idcard'];
                        $user_arr[$mk]['phone'] = $mv['phone'];
                        $user_arr[$mk]['identity_id'] = $mv['identity_id'];
                        $user_arr[$mk]['paper_id'] = $mv['id'];
                        if (in_array($mv['identity_id'],$user_violationinfo_ids)){
                            $user_arr[$mk]['basic_type'] = "异常";
                            $user_arr[$mk]['basic_type_id'] = $user_violationinfo[$mv['identity_id']]['id'];//异常ID
                        }else{
                            $user_arr[$mk]['basic_type'] = "无异常";
                        }
                        if ($mv['status']==1){
                            $user_arr[$mk]['basic_status'] = "正常";
                        }elseif ($mv['status']==2){
                            $user_arr[$mk]['basic_status'] = "作弊";
                        }
                        $user_arr[$mk]['time'] = $this->secToTime($mv['time']);
                        $user_arr[$mk]['basic_start_time'] = date('Y-m-d H:i:s',$mv['starttime']);
                        $user_arr[$mk]['score'] = $mv['modified'];
                        if ($mv['is_read']==3){
                            $user_arr[$mk]['ispass'] = ($mv['modified']>=$mv['passscore'])?"合格":"不合格";
                            $user_arr[$mk]['ispass_status'] = ($mv['modified']>=$mv['passscore'])?1:2;
                        }elseif($mv['is_read']==2){
                            $user_arr[$mk]['ispass'] = "未阅卷";
                            $user_arr[$mk]['ispass_status'] = 3;
                        }else{
                            $user_arr[$mk]['ispass'] = ($mv['modified']>=$mv['passscore'])?"合格":"不合格";
                            $user_arr[$mk]['ispass_status'] = ($mv['modified']>=$mv['passscore'])?1:2;
                        }
                        $user_arr[$mk]['terminal'] = ($mv['terminal']==1)?"手机app":($mv['terminal']==2?"平板app":"pc端");
                    }
                    if ($user_arr) {
                        $result->data = $user_arr;
                        $result->message = json_encode($all_counts);
                        $result->code = 1;
                    } else {
                        $result->code = 0;
                    }
                }else{
//                    $result->message = json_encode($examspapers_model->_db->sql);
                    $result->message = "该考场无人员";
                    $result->code = 0;
                }
            }
//            $result->message = json_encode($basic_user_model);
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

	//查询考场配置
    public function examSelect(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

			$examid = $Exam->id ? $Exam->id : 0;
			$reg = $Exam->username ? $Exam->username : '';
			$basic = new model_newagk_basic();
			$basicrule = new model_newagk_basicrule();

			$condition = ['id'=>$examid];//'admin_reg'=>$reg,

			$items = 'id,basic,status,monitorRule,is_exam,typesId,endtime,starttime,questions as bank_id,ques_name as bank_name,pid,pname,examnumber,archiving,monitor,displayScore';
			$res = $basic->selectOne($condition, $items);
			/**第一步先写配置 end***/
			

            if (!empty($res)) {
				$res['basic'] = htmlspecialchars_decode($res['basic']);
				$res['start'] = [];
				$res['random'] = [];
				$res['end'] = [];
				$rule_arr = $basicrule->select(['basicid'=>$examid])->items;
				foreach($rule_arr as $vb){
					$cmonitorRule =unserialize($vb['monitorRule']);
					$cmonitorRule["verifAble"] = $cmonitorRule["verifAble"]=='true' ? true : false;
					$res[$vb['rule']] = $cmonitorRule;
				}
				//$result->data[] = $res;
				$result->message = json_encode($res);
                $result->code = 1;
            } else {

				$result->message = json_encode([]);
                $result->code = 0;
            }
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	//修改考场配置
    public function examEdit(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {
			$examid = $Exam->id ? $Exam->id : 0;
			$Exam_data = $Exam->filename ? $Exam->filename : [];
			$basic = new model_newagk_basic();
			$qbank =  new model_newagk_qbank();
			$paper = new model_newagk_paper();
			$ques_name = $qbank->selectOne(['id'=>$Exam_data['qid']],'name');
			$paper_name = $paper->selectOne(['id'=>$Exam_data['pid']],'name,settings');
			
			$settings = unserialize($paper_name['settings']);
			$marks = 0;
			foreach($settings as $vs){
				if($vs[0]>3){
					$marks=1;
					break;
				}
			}
			if($marks && !$Exam_data['displayScore']){
				$result->code = 0;
				$result->message = '存在主观或填空题不能设置显示分数';
                $datas[] = ['id' => 0];
				return $result;
				
			}
			
			$monitorRule = 0;
			if(!empty($Exam_data['start'])){
				$Exam_data['start'] = json_decode($Exam_data['start'],true);
				$monitorRule +=1;
			}
			if(!empty($Exam_data['random'])){
				$Exam_data['random'] = json_decode($Exam_data['random'],true);
				$monitorRule +=2;
			}
			if(!empty($Exam_data['end'])){
				$Exam_data['end'] = json_decode($Exam_data['end'],true);
				$monitorRule +=4;
			}
			/**第一步先写配置***/
			$datas = [
					'basic'=>$Exam_data['title'],
					'pid'=>$Exam_data['pid'], //试卷id
					'pname'=>$paper_name['name'], //试卷名
					'questions'=>$Exam_data['qid'], //题库id
					'ques_name'=>$ques_name['name'],
					'starttime'=>$Exam_data['starttime'],
					'endtime'=>$Exam_data['endtime'],
					'eventid'=>$Exam_data['exam_types']>0 ? $Exam_data['eventid'] : 0,
					'examnumber'=>(int)$Exam_data['num'], //考试次数
					'is_exam'=>(int)$Exam_data['is_exam'], //0常规考场，1补考考场
					'displayScore'=>(int)$Exam_data['displayScore'], //0显示分数 1不显示分数
					'archiving'=>(int)$Exam_data['archiving'], //0不归档 1归档、
					'monitor'=>(int)$Exam_data['monitor'], //监控1是启用 0是不启用
					'status'=>(int)$Exam_data['status'],
					'typesId'=>(int)$Exam_data['exam_types'], //1是工程考场 0是普通
					'monitorRule'=>$monitorRule,
					];
		
			 $ret = $basic->update(['id'=>$examid],$datas);//'admin_reg'=>$Exam_data['reg'],

			 if($Exam_data['monitor'] && $examid>0){

				$basicrule = new model_newagk_basicrule();
				$basicrule->delete(array('basicid' => $examid));
				//如果有需要验证就 保存验证规则
				self::ExamRules($examid,$Exam_data);
			 }
			/**第一步先写配置 end***/

       
                $result->code = 1;
           
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

	//修改考场状态
    public function examStatus(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

			$filename = $Exam->filename ? $Exam->filename : [];
			$reg = $Exam->username ? $Exam->username : '';
			$examid = $Exam->field ? explode(',',$Exam->field) : [0];
			$basic = new model_newagk_basic();
			$id = [0];
			foreach($examid as $v){
				$id[] = (int)$v;
			}
			$condition = "id in('".implode("','",$examid)."')";//'admin_reg'=>$reg,
			$res = 0;
			if(!empty($filename)){
				if(!empty($filename['isdelete']) && $filename['isdelete']==3){
					$res = $basic->delete($condition);
				} else {
					$res = $basic->update($condition,$filename);
				}	
			}
            if ($res) {
                $result->code = 1;
				$result->message = '操作成功';
            } else {
                $result->code = 0;
				$result->message = '操作失败';
            } 

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	
	//清空回收站
    public function examEmpty(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {

			$filename = $Exam->id ? $Exam->id : [];
			$platformid = $Exam->filename['platformid'] ? $Exam->filename['platformid'] : [0];
			$basic = new model_newagk_basic();
			$basic->delete(['isdelete'=>1]);//,'platformid'=>$platformid
			$res = 1;
            if ($res) {
                $result->code = 1;
				$result->message = '操作成功';
            } else {
                $result->code = 0;
				$result->message = '操作失败';
            } 

            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }
	
	public function ExamRules($basicid,$Exam_data){
		$basicrule = new model_newagk_basicrule();

		if(!empty($Exam_data['start'])){
			$basicrule->insert(['basicid'=>$basicid,'rule'=>'start','monitorRule'=>serialize($Exam_data['start'])]);
		}
		if(!empty($Exam_data['random'])){
			$basicrule->insert(['basicid'=>$basicid,'rule'=>'random','monitorRule'=>serialize($Exam_data['random'])]);
		}
		if(!empty($Exam_data['end'])){
			$basicrule->insert(['basicid'=>$basicid,'rule'=>'end','monitorRule'=>serialize($Exam_data['end'])]);
		}
	}

    //考试交卷
    public function carryOut(ExaminationRequestDTO $Exam)
    {
        $resultDO = new ResultDO();

        $paper_id= $Exam->filename['paper_id'];
        $basicid= $Exam->filename['basicid'];
        $answer = json_decode($Exam->filename['answer'],true);

        try {
            $examspapers = new model_newagk_examspapers();
            $basic = new model_newagk_basic();
            $paper = new model_newagk_paper();
            $archivesmark = new model_newagk_archivesmark();

            $resultDO->code = 0;
            $resultDO->success = true;
            if (empty($paper_id)) {
                $resultDO->message = "试卷不存在，请刷新再试!";
                return $resultDO;
            }
            $p_setting = $paper->selectOne(" id = (select paperId from agk_exams_papers where id={$paper_id})","settings");
            $question = $examspapers->selectOne(" id={$paper_id}","question");
            $sessionvars = array(
                'setting'=>serialize(['setting'=>$p_setting['settings']]),
                'question'=>$question['question'],
            );
            //$answer = ['65635'=>'B','65622'=>'A']; //临时
            if (is_array($answer)){
                $answer_data = array();
                foreach ($answer as $ank=>$any){
                    if (is_array($any) && isset($any[1])){
                        $answer_data[$ank]['id']=$ank;
                        $answer_data[$ank]['answer'][0]=$any[0];
                        $answer_data[$ank]['answer'][1]=$any[1]?$any[1]:'n';
                    }else{
                        $answer_data[$ank]['id']=$ank;
                        $answer_data[$ank]['answer']=$any[0];
                    }
                }
            }else{
                $answer_data = array();
            }
            $scores = $examspapers->scores($sessionvars,$answer_data,1);// 计算用户的分;
            $basicDetailed = $basic->selectOne(['id'=>$basicid],'displayScore,archiving');

            $args['answer'] = $args['useranswer'] = serialize($answer_data); //用户的答案

            $args['is_read'] = 1;
            $args['modified'] = $args['score'] = $scores['score'];
            $args['pass_questions'] = $scores['pass'];
            $args['nopass_questions'] = $scores['nopass'];
            $pid = $examspapers->update(" id = {$paper_id}",$args);

            /////////////////
            $displayScore = $scores['especially']==3 ? $basicDetailed['displayScore'] : 1;
            ///////////////
            if ($pid){
                if($basicDetailed['archiving'] && $pid){
                    $archivesmark->archives($pid); //单人归档
                }
                $resultDO->data[] = ['displayScore'=>$displayScore];
                $resultDO->message = '阅卷成功';
//                $resultDO->message = json_encode($scores);
                $resultDO->code = 1;
            }else{
                $resultDO->code = 0;
//                $resultDO->message= json_encode($answer);
            }


            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }

    //添加检测记录
    public function addViolation(ExaminationRequestDTO $Exam)
    {
        $resultDO = new ResultDO();
        $data = $Exam->filename;

        try {
            $examspapers = new model_newagk_examspapers();
            $basic = new model_newagk_basic();
            $paper = new model_newagk_paper();
            $violation = new model_newagk_violation();
            $resultDO->code = 0;
            $resultDO->success = true;
            if (!$data['identity_id']) {
                $resultDO->message = "信息不全,添加失败，请刷新再试!";
                return $resultDO;
            }
			$examNum = $examspapers->selectOne(['basicid'=>$data['basicId'],'identity_id'=>$data['identity_id']],'count(*) num');
			$data['remark'] = "第".($examNum['num']+1).'次考试';
            $id = $violation->insert($data);

            ///////////////
            if ($id){
                $resultDO->message = '添加成功';
                $resultDO->message = $id;
                $resultDO->code = 1;
            }else{
                $resultDO->code = 0;
                $resultDO->message= 0;
            }


            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }

    //公布考生成绩
    public function publishUserScore(ExaminationRequestDTO $Exam)
    {
        $resultDO = new ResultDO();

        $basicid= $Exam->filename['basicid'];

        try {
            $basic = new model_newagk_basic();

            $resultDO->code = 0;
            $resultDO->success = true;
            if (empty($basicid)) {
                $resultDO->message = "考场不存在，请刷新再试!";
                return $resultDO;
            }
            $pid = $basic->update(['id'=>$basicid],['displayScore'=>0]);
            ///////////////
            if ($pid){
                $resultDO->message = '公布考生成绩成功';
//                $resultDO->message = json_encode($basic);
                $resultDO->code = 1;
            }else{
                $resultDO->code = 0;
                $resultDO->message= '已经公布考生成绩，请务重复公布！';
            }


            return $resultDO;
        } catch (Exception $e) {
            $resultDO->success = false;
            $resultDO->code = $e->getCode();
        }
        return $resultDO;
    }

    /**
     * 关闭用户考试
     * @param ExaminationRequestDTO $Exam
     * @return ResultDO
     */
    public function examCloseMake(ExaminationRequestDTO $Exam){
        $result = new ResultDO();
        try {

            $id = $Exam->id ? gdl_lib_BaseUtils::getStr($Exam->id) : 0;
            $basicid = $Exam->eveid ? gdl_lib_BaseUtils::getStr($Exam->eveid) : 0;
            $examsession_model = new model_newagk_examsession();
            $violation_model = new model_newagk_violation();
            //查询该记录的用户是否还在考试
                $res = $violation_model->selectOne(['id'=>$id,'status'=>0,'basicId'=>$basicid],'id,identity_id,verification');
                if (isset($res['identity_id'])){
                    $identity_id = $res['identity_id'];
                    $res = $examsession_model->selectOne(['identity_id'=>$identity_id,'basicid'=>$basicid],'es_id,identity_id');
                    if ($res){
						$violation_model->update(['id'=>$id,'basicId'=>$basicid],' status = 1 ');
                        $jpush = new service_jpush();
                        $extras = ['extras'=>['overExam'=>1]];
                        if ($identity_id==1){
                            $identity_id = "one";
                        }
                        $alias = ["{$identity_id}"];
                        //$res = $jpush->jpushAll('接口消息', $extras);  # 推送到所有
                        $res = $jpush->jpushOneMessage('',$alias, $extras);  # 推送到指定用户
                        if($res){
                            $result->code = 1;
                            $result->message ="推送消息成功";
                        }else{
                            $result->code = 0;
                            $result->message = "推送消息失败，接口异常";
                        }
                    }else{
                        $result->code = 0;
                        $result->message = "该用户已经交卷";
                    }
                }else{
                    $result->code = 0;
                    $result->message = "该记录已经被处理";
                }
//            $result->data = $res;
//            $result->message = json_encode($res);
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
	}
	
	//获取历史考场筛选列表
    public function histRoom(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        try {
			$reg = $Exam->username ? $Exam->username : '';
			$archivesmark = new model_newagk_archivesmark();

			$condition ='1';//'admin_reg'=>$reg,

			$items = 'basicId,bankName';
			$res = $archivesmark->select($condition, $items,'group by basicId')->items;
			/**第一步先写配置 end***/
			

            if (!empty($res)) {
				$result->data = $res;
                $result->code = 1;
            } else {

				$result->message = 0;
                $result->code = 0;
            }
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;

            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    /*
    *identify 人脸识别
    */
    public function identify(ExaminationRequestDTO $Exam)
    {
        $result = new ResultDO();
        //如果对比照片其中一项为空，那么直接返回比对失败
        if(empty($Exam->field)||empty($Exam->field))
        {
            $result->success = true;
            $result->code=2;
            $result->data[0] =  array('similarity' => 0);
            $result->message = 'no img';
            return $result;
        }

        try {
            //$res = array();
            $modelSetting = new model_newagk_setting();
            $faceSdkConfig = $modelSetting->selectOne(array('item'=>'0','item_key'=>'facesdk'),'item_value');
            $faceSdk = strtolower($faceSdkConfig['item_value']);
            if(!empty($faceSdk) && $faceSdk=='youtu') $res = YouTu::facecompareOneBase64($Exam->field, $Exam->name);
            elseif(!empty($faceSdk) && $faceSdk=='facevisa') $res = FaceVisa::facecompareOne($Exam->field, $Exam->name);
            else $res = YouTu::facecompareOne($Exam->field, $Exam->name);
            //$res = array('msg'=>$res);
            $result->success = true;
            $result->code=2;
            $result->data[0] = $res;
//            $result->message = json_encode($res);
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        $result->notify_time = time();
        return $result;
    }

    /**
     * 转换数组的键值和键名
     * @param $array
     * @param $item
     * @return array
     */
	private function arrayValueByKey($array,$item='id'){
	    $arr = array();
        if (!$array){
            return $array;
        }
        foreach ($array as $key=>$value){
            if ($item){
                $arr[$value[$item]] = $value;
            }else{
                $arr[$value['id']] = $value;
            }
        }
        return $arr;
    }
    /**
     * 计算剩余天时分。
     * $unixEndTime string 终止日期的Unix时间
     * @author tangxinzhuan
     * @version 2016-10-28
     */
    private function timeRemaining($unixEndTime=0)
    {
        if ($unixEndTime <= time()) { // 如果过了活动终止日期
            return '0天0时0分';
        }

        // 使用当前日期时间到活动截至日期时间的毫秒数来计算剩余天时分
        $time = $unixEndTime - time();

        $days = 0;
        if ($time >= 86400) { // 如果大于1天
            $days = (int)($time / 86400);
            $time = $time % 86400; // 计算天后剩余的毫秒数
        }

        $xiaoshi = 0;
        if ($time >= 3600) { // 如果大于1小时
            $xiaoshi = (int)($time / 3600);
            $time = $time % 3600; // 计算小时后剩余的毫秒数
        }

        $fen = (int)($time / 60); // 剩下的毫秒数都算作分

        return $days.'天'.$xiaoshi.'时'.$fen.'分';
    }

    /**
     *      把秒数转换为时分秒的格式
     *      @param Int $times 时间，单位 秒
     *      @return String
     */
    private function secToTime($times){
        $result = '00:00:00';
        if ($times>0) {
            $hour = floor($times/3600);
            $minute = floor(($times-3600 * $hour)/60);
            $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
            $result = ($hour?$hour:"0").'小时'.$minute.'分'.$second."秒";
        }
        return $result;
    }

    public function isIdCard($id_card){
        if(strlen($id_card)==18){
            return self::idcard_checksum18($id_card);
        }elseif((strlen($id_card)==15)){
            $id_card=self::idcard_15to18($id_card);
            return self::idcard_checksum18($id_card);
        }else{
            return false;
        }
    }
    // 计算身份证校验码，根据国家标准GB 11643-1999
    public function idcard_verify_number($idcard_base){
        if(strlen($idcard_base)!=17){
            return false;
        }
        //加权因子
        $factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
        //校验码对应值
        $verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
        $checksum=0;
        for($i=0;$i<strlen($idcard_base);$i++){
            $checksum += substr($idcard_base,$i,1) * $factor[$i];
        }
        $mod=$checksum % 11;
        $verify_number=$verify_number_list[$mod];
        return $verify_number;
    }
    // 将15位身份证升级到18位
    public function idcard_15to18($idcard){
        if(strlen($idcard)!=15){
            return false;
        }else{
            // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
            if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
                $idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
            }else{
                $idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
            }
        }
        $idcard=$idcard.self::idcard_verify_number($idcard);
        return $idcard;
    }
    // 18位身份证校验码有效性检查
    public function idcard_checksum18($idcard){
        if(strlen($idcard)!=18){
            return false;
        }
        $idcard_base=substr($idcard,0,17);
        if(self::idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
            return false;
        }else{
            return true;
        }
    }

    // 判断是否是手机号码
    function is_mobile( $text ) {
        $search = '/^0?1[3|4|5|6|7|8][0-9]\d{8}$/';
        if ( preg_match( $search, $text ) ) {
            return ( true );
        } else {
            return ( false );
        }
    }
}